package com.lei.zjs.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSON;
import com.lei.zjs.service.ebi.RegionService;
import com.lei.zjs.service.ebi.SubareaService;
import com.lei.zjs.utils.FileUtils;
import com.lei.zjs.vo.Region;
import com.lei.zjs.vo.Subarea;
import com.lei.zjs.web.action.base.BaseAction;

/**
 * 分区管理Action
 * 
 * @author Spinacia
 * 
 */
@Controller
@Scope("prototype")
public class SubareaAction extends BaseAction<Subarea> {

	@Resource
	private SubareaService subareaService;
	
	private File myFile;
	private String myFileFileName;

	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	/**
	 * 添加分区信息
	 */
	public String save() {
		subareaService.save(model);
		return "list";
	}

	/**
	 * 条件分页查询分区信息
	 * 
	 * @throws IOException
	 */
	public String pageQuery() throws IOException {
		DetachedCriteria subareaDC = pageBean.getDetachedCriteria();

		String addresskey = model.getAddresskey();
		if (StringUtils.isNotBlank(addresskey)) {
			subareaDC.add(Restrictions.like("addresskey", "%" + addresskey
					+ "%"));
		}

		Region region = model.getRegion();
		if (region != null) {
			DetachedCriteria regionDC = subareaDC.createCriteria("region");

			String city = region.getCity();
			String province = region.getProvince();
			String district = region.getDistrict();

			if (StringUtils.isNotBlank(province)) {
				regionDC.add(Restrictions
						.like("province", "%" + province + "%"));
			}
			if (StringUtils.isNotBlank(city)) {
				regionDC.add(Restrictions.like("city", "%" + city + "%"));
			}
			if (StringUtils.isNotBlank(district)) {
				regionDC.add(Restrictions
						.like("district", "%" + district + "%"));
			}
		}

		subareaService.pageQuery(pageBean);

		String[] excludes = new String[] { "currentPage", "pageSize",
				"detachedCriteria", "decidedzone", "subareas" };
		this.writeJsonObject2String(pageBean, excludes);
		return NONE;
	}

	/**
	 * 导出分区信息到excel
	 * 
	 * @throws IOException
	 */
	public String exportExcel() throws IOException {
		List<Subarea> list = subareaService.findAll();

		HSSFWorkbook workBook = new HSSFWorkbook();
		HSSFSheet sheet = workBook.createSheet();
		// 创建表标题行
		HSSFRow headRow = sheet.createRow(0);
		headRow.createCell(0).setCellValue("分区编号 ");
		headRow.createCell(1).setCellValue("区域编号");
		headRow.createCell(2).setCellValue("关键字 ");
		headRow.createCell(3).setCellValue("起始号 ");
		headRow.createCell(4).setCellValue("终止号 ");
		headRow.createCell(5).setCellValue("单双号 ");
		headRow.createCell(6).setCellValue("位置 ");

		for (Subarea subarea : list) {
			HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);

			row.createCell(0).setCellValue(subarea.getId());
			row.createCell(1).setCellValue(subarea.getRegion().getId());
			row.createCell(2).setCellValue(subarea.getAddresskey());
			row.createCell(3).setCellValue(subarea.getStartnum());
			row.createCell(4).setCellValue(subarea.getEndnum());
			row.createCell(5).setCellValue(subarea.getSingle());
			row.createCell(6).setCellValue(subarea.getPosition());
		}

		String fileName = "分区数据.xls";
		//对filename进行编码
		fileName = FileUtils.encodeDownloadFilename(fileName, ServletActionContext.getRequest().getHeader("User-Agent"));
		// 要下载,必须要设置两个头,一个流
		OutputStream out = ServletActionContext.getResponse().getOutputStream();
		//设置contentType
		ServletActionContext.getResponse().setContentType(
				ServletActionContext.getServletContext().getMimeType(fileName));
		//设置content-disposition
		ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename="+fileName);
		workBook.write(out);
		return NONE;
	}
	
	/**
	 * 导入分区数据
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public String importExcel() throws FileNotFoundException, IOException{
		String flag = "1";
		Workbook workbook = null;
		List<Subarea> list = new ArrayList<Subarea>();
		try {
			if (myFileFileName.endsWith(".xlsx")) {
				workbook = new XSSFWorkbook(new FileInputStream(myFile)); 
			} else {
				workbook = new HSSFWorkbook(new FileInputStream(myFile)); 
			}
			Sheet sheet = workbook.getSheetAt(0);
			for (Row row : sheet) {
				if (row.getRowNum() == 0) {
					continue;
				}
				String id = row.getCell(0).getStringCellValue();
				String regionId = row.getCell(1).getStringCellValue();
				String addresskey = row.getCell(2).getStringCellValue();
				String startnum = row.getCell(3).getStringCellValue();
				String endnum = row.getCell(4).getStringCellValue();
				String single = row.getCell(5).getStringCellValue();
				String position = row.getCell(6).getStringCellValue();
				
				Subarea subarea = new Subarea();
				subarea.setId(id);
				Region region = new Region();
				region.setId(regionId);
				subarea.setRegion(region);
				subarea.setAddresskey(addresskey);
				subarea.setStartnum(startnum);
				subarea.setEndnum(endnum);
				subarea.setSingle(single);
				subarea.setPosition(position);
				
				list.add(subarea);
			}
			subareaService.importExcel(list);
		} catch (Exception e) {
			flag = "0";
			e.printStackTrace();
		}
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(flag);
		return NONE;
	}

	//通过条件查询分区信息
	public String findSubareaByAjax() throws IOException{
		DetachedCriteria dc = DetachedCriteria.forClass(Subarea.class);
		dc.add(Restrictions.isNull("decidedzone"));
		
		List<Subarea> list = subareaService.findByConditions(dc);
		String json = JSON.toJSONString(list);
		ServletActionContext.getResponse().setContentType("html/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(json);
		return NONE;
	}
}
